import 'package:flutter/material.dart';
import 'package:shortmovieapp/common.dart';
import 'package:shortmovieapp/controller/tikTokVideoListController.dart';
import 'package:shortmovieapp/data/viewData.dart';
import 'package:video_player/video_player.dart';

class myVideoPage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  const myVideoPage({super.key, required this.arguments});

  @override
  State<myVideoPage> createState() => _myVideoPageState();
}

class _myVideoPageState extends State<myVideoPage> {
  VPVideoController? _VPVideoController;

  double videoAspectRatio = 9.0 / 16.0;

  late MovieData? movieData;

  List<String> episodeList = [];
  String? selectedEpisode;

  @override
  void initState() {
    super.initState();
    Debug.log("video page initState begin");

    movieData = widget.arguments["movieDatas"];
    int defaultIndex = widget.arguments["defaultIndex"];

    if (movieData == null || movieData!.videoDatas.isEmpty) return;

    var movieDatas = movieData!.videoDatas;

    int index = defaultIndex;
    if (defaultIndex >= movieDatas.length) {
      index = 0;
    }
    var curItem = movieDatas![index];
    Debug.log("video page initState:${curItem?.url}");
    initVideo(curItem);

    episodeList = List.filled(movieDatas.length, "");
    for (int i = 0; i < episodeList!.length; i++) {
      episodeList![i] = "第${i + 1}集 ${movieDatas[i].title ?? ""}";
    }
    selectedEpisode = episodeList![index];
  }

  void initVideo(VideoData curItem) {
    if (_VPVideoController != null) {
      _VPVideoController?.dispose();
    }
    _VPVideoController = VPVideoController(
      videoInfo: curItem,
      builder: () => VideoPlayerController.network(curItem.url),
      //  () => VideoPlayerController.networkUrl(Uri.(widget.movieData.url)),
    );

    _VPVideoController!.controller.addListener(_didUpdateValue);
    _VPVideoController!.play();

    Debug.log(
        "video play async aspectRatio :${_VPVideoController?.controller.value.aspectRatio}");
  }

  void _didUpdateValue() {
    if (_VPVideoController == null) return;

    double curAspectRatio = _VPVideoController!.controller.value.aspectRatio;
    if (!doubleEqual(videoAspectRatio, curAspectRatio)) {
      setState(() {
        videoAspectRatio = _VPVideoController!.controller.value.aspectRatio;
        Debug.log(
            "video controller _didUpdateValue update aspectRatio:${_VPVideoController?.controller.value.aspectRatio}");
      });
    }
    //Debug.log("video controller _didUpdateValue:${_VPVideoController?.controller.value.aspectRatio}");
  }

  @override
  void dispose() {
    _VPVideoController?.pause();
    _VPVideoController?.dispose();

    Debug.log("video page on dispose");
    super.dispose();
  }

  void onClickOperate() {
    Debug.log("on click operate");
  }

  void onClickFullScreen() {
    Debug.log("on click FullScreen");
  }

  @override
  Widget build(BuildContext context) {
    VideoPlayerController? videoController = null;
    if (_VPVideoController != null) {
      videoController = _VPVideoController!.controller;

      videoAspectRatio = videoController.value.aspectRatio;
      Debug.log(
          "video page build aspectRatio:${videoController.value.aspectRatio}");
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(
          selectedEpisode ?? "",
          style: const TextStyle(fontSize: 14),
        ),
        actions: [
          IconButton(
              onPressed: onClickOperate, icon: const Icon(Icons.more_vert))
        ],
      ),
      body: Stack(
        children: [
          Center(
            child: AspectRatio(
              aspectRatio: videoAspectRatio,
              child: videoController != null
                  ? VideoPlayer(videoController)
                  : const Text("视频播放出错"),
            ),
          ),
          //Center(child:

          //),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
                width: double.maxFinite,
                height: 70,
                alignment: Alignment.topCenter,
                color: Colors.black12,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      width: 200,
                      padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
                      height: 60,
                      alignment: Alignment.center,
                      child: DropdownButton<String>(
                        underline: const SizedBox(),
                        padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                        hint: Text("选集·共${episodeList.length}集"),
                        value: selectedEpisode,
                        onChanged: (String? newValue) {
                          setState(() {
                            selectedEpisode = newValue!;
                            int index = episodeList.indexOf(newValue);
                            Debug.log("选择:${selectedEpisode}  index:${index}");
                            if (index >= 0) {
                              if (movieData != null) {
                                initVideo(movieData!.videoDatas[index]);
                              }
                            }
                          });
                        },
                        items: episodeList
                            .map<DropdownMenuItem<String>>((String value) {
                          return DropdownMenuItem<String>(
                            value: value,
                            child: Text(
                              value,
                              style: const TextStyle(fontSize: 12),
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                    IconButton(
                        onPressed: onClickFullScreen,
                        icon: const Icon(Icons.fullscreen))
                  ],
                )),
          )
        ],
      ),
      //bottomSheet:
    );
  }
}
